const http = require('http');
const fs = require('fs').promises; 
const path = require('path');

const hostsFilePath = path.join(process.env.SystemRoot, 'System32', 'drivers', 'etc', 'hosts');
const trafficLogPath = 'traffic.log';
let history = [];

const logTraffic = async (logEntry) => {
    console.log('流量记录:', logEntry);
};

const addHostEntry = async (entry) => {
    try {
        await fs.appendFile(hostsFilePath, entry + '\n');
        history.push(entry);
        return '成功添加条目到 hosts 文件: ' + entry;
    } catch (err) {
        throw new Error('写入 hosts 文件失败: ' + err);
    }
};

const clearHostEntry = async (entry) => {
    try {
        const data = await fs.readFile(hostsFilePath, 'utf8');
        const updatedData = data.split('\n').filter(line => line.trim() !== entry).join('\n');
        await fs.writeFile(hostsFilePath, updatedData);
        return '成功删除条目: ' + entry;
    } catch (err) {
        throw new Error('清除 hosts 文件条目失败: ' + err);
    }
};

const requestHandler = async (req, res) => {
    if (req.method === 'POST' && req.url === '/add') {
        let body = '';

        req.on('data', chunk => {
            body += chunk.toString();
        });

        req.on('end', async () => {
            const newEntry = body.split('=')[1].replace(/\+/g, ' ');
            try {
                const message = await addHostEntry(newEntry);
                await logTraffic(newEntry);
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                res.end(message);
            } catch (error) {
                res.writeHead(500);
                res.end(error.message);
            }
        });
    } else if (req.method === 'POST' && req.url === '/clear') {
        let body = '';

        req.on('data', chunk => {
            body += chunk.toString();
        });

        req.on('end', async () => {
            const entryToClear = body.split('=')[1].replace(/\+/g, ' ');
            try {
                const message = await clearHostEntry(entryToClear);
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                res.end(message);
            } catch (error) {
                res.writeHead(500);
                res.end(error.message);
            }
        });
    } else if (req.method === 'GET') {
        try {
            const data = await fs.readFile('index.html');
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(data);
        } catch (err) {
            res.writeHead(500);
            res.end('Error loading index.html');
        }
    } else {
        res.writeHead(405); // Method Not Allowed
        res.end('Method Not Allowed');
    }
};

const server = http.createServer(requestHandler);

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`FOHost is running at http://localhost:${PORT}`);
});
